#! /bin/sh

echo "Initializing nwolf, please wait ..."

mkdir -p /dev/pts /etc /root /sys /proc /tmp /var/lock
mount -t sysfs -o nodev,noexec,nosuid sysfs /sys
mount -t proc  -o nodev,noexec,nosuid proc /proc

# mount `devtmpfs' may fail, but `null' still doesn't exist ...
if ! mount -t devtmpfs -o mode=0755 devtmpfs /dev; then
	# Kernel doesn't support `devtmpfs', try `tmpfs'
	mount -t tmpfs -o size=10M,mode=0755 tmpfs /dev
	[ -e /dev/console ] || mknod -m 0600 /dev/console c 5 1
	[ -e /dev/null ] || mknod -m 0666 /dev/null c 1 3
fi

# devpts: pseudo terminal fs
[ -d /dev/pts ] || mkdir -p /dev/pts
mount -t devpts -o noexec,nosuid,gid=5,mode=0644 devpts /dev/pts || true

# /bin/sh -i </dev/console >/dev/console 2>&1

. /scripts/functions

paras_list="
	break=
	debug=
	quiet=
	root_rw=
	vroot_dev=
	init=/sbin/init
	ip=
	nfsroot=
	rootdelay=
	rootflags=
	rootfstype=
	rootwait=
	panic=
"

export $paras_list

# conf_load <dir> <file>
conf_load() { [ -z "${2%%*.conf}" ] && . "$1/$2"; }
traverse_recursive "conf_load" "/conf"

# reference to Documentation/kernel-parameters.txt for details
# all paras will be exported in 
for x in $(cat /proc/cmdline); do
	k=${x%%=*}; v=${x#*=}
	case "$k" in
	break)	#	<-- used to debug the script self
		[ -n "$v" ] || v=premount; break=$v
		;;
	debug)
		debug=y; quiet=n
		set -x	# <-- open shell debug
		;;
	quiet)
		quiey=y;
		;;
	ro|rw)
		root_rw=$k
		;;
	init|ip|nfsroot|root|rootdelay|rootflags|rootfstype|rootwait|panic)
		eval $k=$v
		;;
	rootdelay|rootwait|panic)
		eval $k=${v##*[![:digit:]]*}	# <-- digit or empty
		;;
	esac
done

# top: prepare; rootfs: mount; bottom: clean
run_scripts top
run_scripts rootfs
run_scripts bottom
unset $paras_list

[ -e /sys/block/sda ] || /bin/sh
mount -t ext4 /dev/sda8 /root 2>/dev/null ||
	mount -t ext4 /dev/sda /root || /bin/sh
mount -o move /dev /root/dev
mount -o move /proc /root/proc
mount -o move /sys /root/sys
exec chroot /root /sbin/init </dev/console >/dev/console 2>&1

/bin/sh
/bin/sh

panic "pivot should never return"
